﻿using System.Collections;
using AutoMapper;

namespace Xman.Extensions.AutoMapper;


public static class AutoMapperExtensions
{

    public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
    {
        var sourceType = source.GetType().GetGenericArguments()[0];
        var config = new MapperConfiguration(ctx => { ctx.CreateMap(sourceType, typeof(TDestination)); });
        var mapper = config.CreateMapper();
        return mapper.Map<List<TDestination>>(source);
    }


    public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
    {
        var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(TSource), typeof(TDestination)));
        var mapper = config.CreateMapper();
        return mapper.Map<List<TDestination>>(source);
    }


    public static TDestination MapTo<TDestination>(this object source) where TDestination : class
    {
        if (source == null)
        {
            return default;
        }
        var config = new MapperConfiguration(ctx => { ctx.CreateMap(source.GetType(), typeof(TDestination)); });
        var mapper = config.CreateMapper();
        return mapper.Map<TDestination>(source);
    }


    public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)where TSource : class where TDestination : class
    {
        if (source == null)
        {
            return destination;
        }

        var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(TSource), typeof(TDestination)));
        var mapper = config.CreateMapper();
        return mapper.Map<TDestination>(source);
    }
}
